import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { NzNotificationService } from 'ng-zorro-antd';
import {MessageService} from 'primeng/api';
import { AuthService } from 'src/app/service/auth.service';
import { JsonResult } from 'src/app/model/JsonResult';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers:[MessageService]
})
export class LoginComponent implements OnInit {

  loginForm:FormGroup;

  @ViewChild("userid",{static:false})
  private userid_er:ElementRef

  private userid$ = new Subject();

  constructor(
    private fb:FormBuilder,
    private noti:NzNotificationService,
    private msgService:MessageService,
    private authService:AuthService
  ) { 
    this.initLoginForm();// 初始化登录表单
    this.initRx();// 初始化 rx 对象
  }

  ngOnInit() {
  }

  initLoginForm(){
    this.loginForm = this.fb.group({
      userid:[null,Validators.required],
      userName:[{value:null,disabled:true},Validators.required],
      password:[null,Validators.required]
    });
  }


  // 注册 rx 类型的对象
  initRx(){
    this.userid$.pipe(debounceTime(1000)).subscribe(
      (val:string) => {
        // this.msg('工号：' + val);
        this.primeMsg('工号：' + val);
      }
    )
  }


  useridChange(e){
    this.userid$.next(e);
  }

  msg(content:string){
    this.noti.blank(
      '通知',content
    )
  }

  // 登录表单提交
  submitForm(){
    let userid = this.loginForm.value["userid"];
    let password = this.loginForm.value["password"];

    
    this.authService.login(userid,password).subscribe(
      (res:JsonResult)=> {
        if( !res ){
          this.primeMsg("返回数据异常！");
          return;
        }

        if( res.code !== 1 ){
          this.primeMsg("账号或密码错误！");
          return;
        }

        // 登录成功则跳转到首页
        this.authService.isLoggedIn = true;
        this.primeMsg("登录成功！");
        this.authService.gotoIndex();
        
      },error=>this.primeMsg("登录失败！")
    )
  }

  // 自定义渐变色消息通知
  primeMsg(content:string) {
    this.msgService.add({key: 'custom', severity:'info', summary: '通知', detail:content});
  }

}
